//
//  PieChartVC.m
//  Wallets Manager
//
//  Created by Nguyen Chi Cong on 10/21/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

typedef enum {
	RTMMonth = 0, 
	RTMQuarter,
    RTMCustom,
} ReportTimeModeType;

#import "PieChartVC.h"
#import "CPTLayer+MoveAnimation.h"
#import "ChangeTimeVC.h"
#import "QuickViewTransactionVC.h"
#import "DataBaseAccess.h"
#import "folyAppDelegate.h"
#import "Global.h"

@implementation PieChartVC
{
    NSTimer *timerHide;
    SVSegmentedControl *grayRC;
    NSInteger currentTimeMode;
    ChangeTimeVC *changTimeModeVC;
    NSDate *fromDate;
    NSDate *toDate;
    NSDateFormatter *dateFormatter;
}
@synthesize hostView;
@synthesize btnShow;
@synthesize segSelector;
@synthesize listSymbols;
@synthesize valueOfSymbols;
@synthesize listColor;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    fromDate = [NSDate firstDayOfCurrentMonth];
    toDate   = [NSDate firstDayOfNextMonth];
    [super viewDidLoad];
   
    //Init segment control
    grayRC = [[SVSegmentedControl alloc] initWithSectionTitles:[NSArray arrayWithObjects:@"Income", @"Expense", nil]];
    [grayRC addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    
	grayRC.font = [UIFont boldSystemFontOfSize:12];
	grayRC.titleEdgeInsets = UIEdgeInsetsMake(0, 14, 0, 14);
	grayRC.height = 30;
	
	grayRC.thumb.tintColor = [UIColor colorWithRed:0 green:0.5 blue:0.1 alpha:1];
	
	[self.view addSubview:grayRC];
	
	grayRC.center = CGPointMake(160, 62);
    
    //init color
    listColor = [[NSMutableArray alloc] init];
    CPTColor *color1 = [CPTColor redColor];
    [listColor addObject:color1];
    
    CPTColor *color3 = [CPTColor greenColor];
    [listColor addObject:color3];
    CPTColor *color4 = [CPTColor yellowColor];
    [listColor addObject:color4];
    CPTColor *color5 = [CPTColor blueColor];
    [listColor addObject:color5];
    CPTColor *color6 = [CPTColor magentaColor];
    [listColor addObject:color6];
    CPTColor *color7 = [CPTColor brownColor];
    [listColor addObject:color7];
    CPTColor *color2 = [CPTColor grayColor];
    [listColor addObject:color2];
    
    CPTColor *color9 = [CPTColor purpleColor];
    [listColor addObject:color9];
    CPTColor *color10 = [CPTColor orangeColor];
    [listColor addObject:color10];
    CPTColor *color11 = [CPTColor lightGrayColor];
    [listColor addObject:color11];
    CPTColor *color8 = [CPTColor cyanColor];
    [listColor addObject:color8];
    CPTColor *color12 = [CPTColor blackColor];
    [listColor addObject:color12];
    [self initPlot];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTimeMode:) name:@"ChangeTimeMode" object:nil];
    
    currentTimeMode = RTMMonth;
    dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
}

- (void)segmentedControlChangedValue:(SVSegmentedControl*)segmentedControl
{
    [timerHide invalidate];
    
    if([segmentedControl selectedIndex] == 0)
    {
        [self loadIncome];
    }else
    {
        [self loadExpense];
    }
}

- (void)viewDidUnload
{
    [self setBtnShow:nil];
    [self setSegSelector:nil];
    [super viewDidUnload];
    timerHide           = nil;
    listSymbols         = nil;
    valueOfSymbols      = nil;
    listColor           = nil;
    grayRC              = nil;
    fromDate            = nil;
    toDate              = nil;
    changTimeModeVC     = nil;
    dateFormatter       = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ChangeTimeMode" object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    if([grayRC selectedIndex] == 0)
    {
        [self loadIncome];
    }else
    {
        [self loadExpense];
    }
    [super viewWillAppear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Chart behavior
-(void)initPlot {
    [self configureHost];
    [self configureGraph];
    [self configureChart];
    [self configureLegend];
}

-(void)configureHost { 
//    // 1 - Set up view frame
//    CGRect parentRect = self.view.bounds;
//    CGSize toolbarSize = CGSizeMake(320, 80);
//    parentRect = CGRectMake(parentRect.origin.x, 
//                            (parentRect.origin.y + toolbarSize.height), 
//                            parentRect.size.width, 
//                            (parentRect.size.height - toolbarSize.height));
//    // 2 - Create host view
//    self.hostView = [(CPTGraphHostingView *) [CPTGraphHostingView alloc] initWithFrame:parentRect];
//    self.hostView.allowPinchScaling = NO;
//    [self.view addSubview:self.hostView];
}

-(void)configureGraph { 
    
    //    // 1 - Create and initialize graph
    CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
    self.hostView.hostedGraph = graph;
    graph.paddingLeft = 1.0f;
    graph.paddingTop = 1.0f;
    graph.paddingRight = 1.0f;
    graph.paddingBottom = 1.0f;
    graph.axisSet = nil;
    // 2 - Set up text style
    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
    textStyle.color = [CPTColor blackColor];
    textStyle.fontName = @"Helvetica-Bold";
    textStyle.fontSize = 14.0f;
    // 3 - Configure title
    NSDate *tempDate;
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:toDate];
    NSInteger day = [components day];
    day--;
    [components setDay:day];
    tempDate = [gregorianCalendar dateFromComponents:components];
    NSString *title = [NSString stringWithFormat:@"Proportion from %@ to %@", [dateFormatter stringFromDate:fromDate], [dateFormatter stringFromDate:tempDate]];
    graph.title = title;    
    graph.titleTextStyle = textStyle;
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;    
    graph.titleDisplacement = CGPointMake(0.0f, -12.0f);         
    // 4 - Set theme
    [graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
    
}

-(void)configureChart { 
    // 1 - Get reference to graph
    CPTGraph *graph = self.hostView.hostedGraph;    
    // 2 - Create chart
    CPTPieChart *pieChart = [[CPTPieChart alloc] init];
    pieChart.dataSource = self;
    pieChart.delegate = self;
    pieChart.pieRadius = (self.hostView.bounds.size.height * 0.5) / 2;
    pieChart.identifier = graph.title;
    pieChart.startAngle = M_PI_4;
    pieChart.sliceDirection = CPTPieDirectionClockwise;    
    // 3 - Create gradient
    CPTGradient *overlayGradient = [[CPTGradient alloc] init];
    overlayGradient.gradientType = CPTGradientTypeRadial;
    overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.9];
    overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.4] atPosition:1.0];
    pieChart.overlayFill = [CPTFill fillWithGradient:overlayGradient];
    // 4 - Add chart to graph    
    [graph addPlot:pieChart];
}

-(void)configureLegend {
    // 1 - Get graph instance
    CPTGraph *graph = self.hostView.hostedGraph;
    // 2 - Create legend
    CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];
    // 3 - Configure legend
    theLegend.numberOfColumns = 1;
    theLegend.numberOfRows = [listSymbols count];
    theLegend.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
    theLegend.borderLineStyle = [CPTLineStyle lineStyle];
    theLegend.cornerRadius = 5.0;
    // 4 - Add legend to graph
    graph.legend = theLegend;     
    graph.legendAnchor = CPTRectAnchorBottomRight;
    //CGFloat legendPadding = -(self.view.bounds.size.width / 12);
    graph.legendDisplacement = CGPointMake(-10, 10);
    
    if(![timerHide isValid])
        timerHide = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideLegend) userInfo:nil repeats:NO];
    
}

-(void)hideLegend
{    
    CPTGraph *graph = self.hostView.hostedGraph;
    CPTLegend *legend = graph.legend;
    
    CGPoint pointBefore = legend.position;
    //NSLog(@"POINT %f X %f", pointBefore.x, pointBefore.y);
    CGFloat xPoint = legend.frame.size.width - 18;
    
    CGPoint newPoint = CGPointMake(pointBefore.x + xPoint, pointBefore.y);
    //NSLog(@"AFTER : %f %f", newPoint.x, newPoint.y);
    [legend moveLayer:legend to:newPoint];

    btnShow.hidden = NO;

}

#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    return [listSymbols count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
    if (CPTPieChartFieldSliceWidth == fieldEnum) 
    {
        return [valueOfSymbols objectAtIndex:index];
    }
    return [NSDecimalNumber zero];
}

-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index {

    
    
    // 1 - Define label text style
    static CPTMutableTextStyle *labelText = nil;
    if (!labelText) {
        labelText= [[CPTMutableTextStyle alloc] init];
        labelText.fontSize = 15.f;
        labelText.color = [CPTColor blackColor];
    }
    // 2 - Calculate portfolio total value
    NSDecimalNumber *portfolioSum = [NSDecimalNumber zero];
    for (NSDecimalNumber *price in valueOfSymbols) {
        portfolioSum = [portfolioSum decimalNumberByAdding:price];
    }
    // 3 - Calculate percentage value
    NSDecimalNumber *price = [valueOfSymbols objectAtIndex:index];
    NSDecimalNumber *percent = [price decimalNumberByDividingBy:portfolioSum];
    // 4 - Set up display label
    
    NSString *labelValue;
    if([percent doubleValue]*100.0f < 1.0f)
    {
        labelValue = @"";

    }else
    {
        labelValue = [NSString stringWithFormat:@"%0.1f %%", ([percent floatValue] * 100.0f)];
    }
    
    if([((folyAppDelegate *)[[UIApplication sharedApplication]delegate]).noData boolValue])
    {
        labelValue = @"";
    }
   
    // 5 - Create and return layer with label text
    
    return [[CPTTextLayer alloc] initWithText:labelValue style:labelText];
}

-(NSString *)legendTitleForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index {
    if (index < [listSymbols count]) {
        return [listSymbols objectAtIndex:index];
    }
    return @"N/A";
}

#pragma mark - IBAction
- (IBAction)changeTime:(id)sender {
    
//    alert	= [[SBTableAlert alloc] initWithTitle:@"Report Timing" cancelButtonTitle:@"Cancel" messageFormat:@"Select Time Mode!"];
//    [alert setType:SBTableAlertTypeSingleSelect];
//    //[alert.view addButtonWithTitle:@"OK"];
//    [alert setDelegate:self];
//	[alert setDataSource:self];
//	
//	[alert show];
    
    if(!changTimeModeVC)
    {
        changTimeModeVC = [[ChangeTimeVC alloc] initWithNibName:@"ChangeTimeVC" bundle:nil ];
        [changTimeModeVC.view setFrame:CGRectMake(0, 480, 320, 460)];
        //[self.navigationController.view addSubview:changTimeModeVC.view];
        [gTabBarController.view addSubview:changTimeModeVC.view];
    }
    
    [UIView beginAnimations:@"push_animation" context:NULL];
    [UIView setAnimationDuration:0.1];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    [changTimeModeVC.view setFrame:CGRectMake(0, 20, 320, 460)];
    
    [UIView commitAnimations];
    
}

-(IBAction)backPreviousView:(id)sender
{
    //self.hidesBottomBarWhenPushed = NO;
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(IBAction)showLegend:(id)sender
{
    btnShow.hidden = YES;
    [self performSelector:@selector(showLegend)];
}

-(void)showLegend
{
    
    CPTGraph *graph = self.hostView.hostedGraph;
    CPTLegend *legend = graph.legend;
    
    CGPoint pointBefore = legend.position;
    //NSLog(@"POINT %f X %f", pointBefore.x, pointBefore.y);
    CGFloat xPoint = legend.frame.size.width - 18;
    
    CGPoint newPoint = CGPointMake(pointBefore.x - xPoint, pointBefore.y);
    //NSLog(@"AFTER : %f %f", newPoint.x, newPoint.y);
    [legend moveLayer:legend to:newPoint];
    timerHide = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideLegend) userInfo:nil repeats:NO];
}

-(IBAction)switchType:(id)sender
{
    [timerHide invalidate];
    UISegmentedControl *seg = (UISegmentedControl *)sender;
    if([seg selectedSegmentIndex] == 0)
    {
        [self loadIncome];
    }else
    {
        [self loadExpense];
    }
}

#pragma mark - CPTPieChartDelegate
-(void)pieChart:(CPTPieChart *)plot sliceWasSelectedAtRecordIndex:(NSUInteger)index
{
    
    NSLog(@"DATA = %@", ((folyAppDelegate *)[[UIApplication sharedApplication]delegate]).noData);
    
    if([((folyAppDelegate *)[[UIApplication sharedApplication]delegate]).noData boolValue])
    {
        
        UIAlertView *alert = nil;
        if(!alert)
        {
            alert = [[UIAlertView alloc] initWithTitle:@"Notification" message:@"No DATA !" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
            
            [alert show];
        }
        return;
    }
   
    NSLog(@"SELECT RECORD %i", index);
    NSLog(@"%@", [listSymbols objectAtIndex:index]);
    NSString *nameType = [listSymbols objectAtIndex:index];
    NSArray *inputs;
    switch ([grayRC selectedIndex]) {
        case 0:
        {
            IncomeType *type = [DataBaseAccess iTypeForName:nameType];
            Wallet *w = ((folyAppDelegate *)[[UIApplication sharedApplication]delegate]).currentWallet;
            inputs = [DataBaseAccess getAllIncomesOfType:type inWallet:w inTimeFrom:fromDate to:toDate];
        }
            break;
            
        case 1:
        {
            ExpenseType *type = [DataBaseAccess eTypeForName:nameType];
            Wallet *w = ((folyAppDelegate *)[[UIApplication sharedApplication]delegate]).currentWallet;
            inputs = [DataBaseAccess getAllExpensesOfType:type inWallet:w inTimeFrom:fromDate to:toDate];
        }
            break;
            
        default:
            break;
    }
    
    QuickViewTransactionVC *qvt = [[QuickViewTransactionVC alloc] initWithNibName:@"QuickViewTransactionVC" bundle:nil];
    qvt.total = [valueOfSymbols objectAtIndex:index];
    qvt.arrInputs = inputs;
    qvt.fromDate = fromDate;
    qvt.toDate = toDate;
    qvt.reportType = [grayRC selectedIndex];
    qvt.name = nameType;
    [self presentModalViewController:qvt animated:YES];
}

-(void)loadIncome
{
    listSymbols = [[CPDStockPriceStore sharedInstance] tickerSymbols];
    valueOfSymbols = [[CPDStockPriceStore sharedInstance] numberForIncomeSymbolsFromDate:fromDate toDate:toDate];
    [self.hostView.hostedGraph reloadData];
    [self initPlot];
}

-(void)loadExpense
{
    listSymbols = [[CPDStockPriceStore sharedInstance] expenseSymbols];
    valueOfSymbols = [[CPDStockPriceStore sharedInstance] numberForExpenseSymbolsFromDate:fromDate toDate:toDate];
    [self.hostView.hostedGraph reloadData];
    [self initPlot];
}

#pragma mark - Pie Chart Data Source
-(CPTFill *)sliceFillForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index
{
    return [[CPTFill alloc] initWithColor:[listColor objectAtIndex:index]];
}

#pragma mark - Notification Center Delegate
-(void)changeTimeMode:(NSNotification *)notification
{
    NSLog(@"OBJECT = %@", notification.object);
    currentTimeMode = [notification.object intValue];
    fromDate = [notification.userInfo valueForKey:@"fromDate"];
    toDate = [notification.userInfo valueForKey:@"toDate"];
    NSLog(@"FROM = %@", [dateFormatter stringFromDate:fromDate]);
    NSLog(@"TO = %@", [dateFormatter stringFromDate:toDate]);
    if([grayRC selectedIndex] == 0)
    {
        [self loadIncome];
    }else
    {
        [self loadExpense];
    }
}










@end
